
************************************************************
* Regressions and Figures
************************************************************

cd "$FOLDER"
use aggregate_INS_all, clear   /* 3-D level : Performance computed against all counterparties */


*-----------------------------------------------------------*
* Rename to shorten variable names
*-----------------------------------------------------------*
forvalues i = 0/30 {
    capture rename dimTS`i'ClientUnw      dim`i'Unw
    capture rename dimTS`i'ClientWeighted dim`i'W
}


*-----------------------------------------------------------*
* Winsorise (Weighted series)
*-----------------------------------------------------------*
global winlist "W"
foreach x of global winlist {
    forvalues i = 0/30 {
        capture confirm variable dim`i'`x'
        if !_rc {
            quietly _pctile dim`i'`x', p(1 99)
            scalar p1 = r(r1)
            scalar p99 = r(r2)
            replace dim`i'`x' = p99 if dim`i'`x' > p99 & dim`i'`x' < .
            replace dim`i'`x' = p1  if dim`i'`x' < p1
        }
    }
}


*-----------------------------------------------------------*
* Define the 2 controls (safe logs)
*-----------------------------------------------------------*
gen size    = log(clientQuantityDaily) if clientQuantityDaily > 0
gen logTRAN = log(transactionDaily)    if transactionDaily > 0


* Winsorise selected covariates
global winlist "day_OR1_bip day_OR1_ful day_INS_ful day_INS_bip logTRAN size"
foreach x of global winlist {
    capture confirm variable `x'
    if !_rc {
        quietly _pctile `x', p(1 99)
        scalar p1 = r(r1)
        scalar p99 = r(r2)
        replace `x' = p99 if `x' > p99 & `x' < .
        replace `x' = p1  if `x' < p1
    }
}


drop mm
gen mm = tradedate


**********************
* Table 3 *
**********************
global vars "5 10 15"
local gg = 1

foreach j of global vars {
    di `gg'

    cap drop yy* zz*
    gen yy = 100 * dim`j'W
    capture confirm variable dim`j'Unw
    if !_rc {
        gen zz = 100 * dim`j'Unw
    }

    cap drop R_*
    gen R_cent_ful = day_INS_ful
    gen R_cent_bip = day_INS_bip
    gen R_size     = size
    gen R_tran     = logTRAN

    ***  RATING
    capture confirm variable ig
    if !_rc {
        gen R_cent_ful_ig = R_cent_ful * ig
        gen R_cent_bip_ig = R_cent_bip * ig
    }
    capture confirm variable hy
    if !_rc {
        gen R_cent_ful_hy = R_cent_ful * hy
        gen R_cent_bip_hy = R_cent_bip * hy
    }

    ***  CDS
    capture confirm variable cds
    if !_rc {
        gen R_cent_ful_cds = R_cent_ful * cds
        gen R_cent_bip_cds = R_cent_bip * cds
    }

    **** Table 3 Panel A: baseline (Weighted)
    reghdfe yy R_cent_ful R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    estimates store aa`gg'

    reghdfe yy R_cent_bip R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    estimates store bb`gg'

    **** Table 3 Panel B: CDS (Weighted)
    capture noisily reghdfe yy R_cent_ful R_cent_ful_cds R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    if _rc == 0 estimates store ii`gg'

    capture noisily reghdfe yy R_cent_bip R_cent_bip_cds R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    if _rc == 0 estimates store jj`gg'

    **** Table 3 Panel C: IG vs HY (Weighted)
    capture noisily reghdfe yy R_cent_ful R_cent_ful_ig R_cent_ful_hy R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    if _rc == 0 estimates store ee`gg'

    capture noisily reghdfe yy R_cent_bip R_cent_bip_ig R_cent_bip_hy R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    if _rc == 0 estimates store ff`gg'

    local gg = `gg' + 1
}

* Export results
global ress "aa bb ii jj ee ff"
foreach j of global ress {
    esttab `j'* , star("*" 0.1 "**" 0.05 "***" 0.01) b(%10.4f) t(%10.2f) ///
        scalars(N r2) sfmt(%10.3f) mtitles replace
}


*********************************************
** Figure 1 - Step 30-day Performance
*********************************************
cap drop h bC* bT* up90b* lo90b*
gen h = _n - 1
quietly gen bTRAN = .
quietly gen bCENT = .
quietly gen up90bCENT = .
quietly gen lo90bCENT = .
quietly gen up90bTRAN = .
quietly gen lo90bTRAN = .

forvalues i = 0/30 {
    di `i'
    qui {
        cap drop aux* yy
        gen yy = 100 * dim`i'W
        gen auxxx = day_INS_bip
        local shock auxxx

        reghdfe yy `shock' size if active == 1 & transactionDaily > 0, ///
            absorb(mm#call instrumentid#dyear) vce(cluster call mm)
        gen aux1 = _b[`shock']
        gen aux2 = _se[`shock']

        reghdfe yy `shock' size if active == 0 & transactionDaily > 0, ///
            absorb(mm#call instrumentid#dyear) vce(cluster call mm)
        gen aux3 = _b[`shock']
        gen aux4 = _se[`shock']

        scalar sig1 = 0.10
        quietly replace bCENT       = aux1 if h == `i'
        quietly replace up90bCENT   = aux1 + invnormal(1 - sig1/2) * aux2 if h == `i'
        quietly replace lo90bCENT   = aux1 - invnormal(1 - sig1/2) * aux2 if h == `i'

        quietly replace bTRAN       = aux3 if h == `i'
        quietly replace up90bTRAN   = aux3 + invnormal(1 - sig1/2) * aux4 if h == `i'
        quietly replace lo90bTRAN   = aux3 - invnormal(1 - sig1/2) * aux4 if h == `i'
    }
}

cap drop bzero
gen bzero = 0


tw (scatter up90bCENT h, connect(l) lpattern(dash) msymbol(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter lo90bCENT h, connect(l) lpattern(dash) msymbol(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter bCENT h, connect(l) msymbol(circle) msize(1.8) mcolor(black) lcolor(black) lwidth(medthick)) ///
   (line bzero h, lcolor(red)) if h <= 25, ///
   title("Client-Day-Bond Level", size(medlarge)) ///
   graphregion(color(white)) legend(off) ///
   xtitle("TRADING DAYS", size(medium)) ///
   name("dash_33bsip", replace)


graph export BASELINE_2021_3d.pdf, replace


**************************
* Table 4 Panel A: DOWNGRADES
**************************



** Flag Rating DOWNGRADE
cap drop DO_flag5
gen byte DO_flag5 = .
replace DO_flag5 = 0 if flag5_rating == 0
replace DO_flag5 = 1 if flag5_rating == -1


cap estimates drop dd*
cap estimates drop ee*
global vars3 "dim6Unw dim7Unw dim8Unw"

local gg = 1
foreach j of global vars3 {
    di `gg'
    cap drop yy
    gen yy = 100 * `j'


    qui reghdfe yy i.Dum_2D_ful##i.DO_flag5 size ///
        if active == 1 & flag_noRatChange == ., ///
        absorb(instrumentid#dyear tradedate call#dyear) vce(cluster call tradedate)
    qui estimates store dd`gg'

    qui reghdfe yy i.Dum_2D_bip##i.DO_flag5 size ///
        if active == 1 & flag_noRatChange == ., ///
        absorb(instrumentid#dyear tradedate call#dyear) vce(cluster call tradedate)
    qui estimates store ee`gg'

    local gg = `gg' + 1
}

* Export results
global ress "dd ee"
foreach j of global ress {
    esttab `j'* , star("*" 0.1 "**" 0.05 "***" 0.01) b(%10.4f) t(%10.2f) ///
        scalars(N r2) sfmt(%10.3f) mtitles replace
}


**************************
* Table 4 Panel B: UPGRADES
**************************

** Flag Rating UPGRADE
cap drop UP_flag5
gen byte UP_flag5 = .
replace UP_flag5 = 0 if flag5_rating == 0
replace UP_flag5 = 1 if flag5_rating == 1

cap estimates drop cc*
cap estimates drop bb*
global vars3 "dim6Unw dim7Unw dim8Unw"

local gg = 1
foreach j of global vars3 {
    di `gg'
    cap drop yy
    gen yy = 100 * `j'


    qui reghdfe yy i.Dum_2D_ful##i.UP_flag5 size ///
        if active == 1 & flag_noRatChange == ., ///
        absorb(instrumentid#dyear tradedate call#dyear) vce(cluster call tradedate)
    qui estimates store bb`gg'

    qui reghdfe yy i.Dum_2D_bip##i.UP_flag5 size ///
        if active == 1 & flag_noRatChange == ., ///
        absorb(instrumentid#dyear tradedate call#dyear) vce(cluster call tradedate)
    qui estimates store cc`gg'

    local gg = `gg' + 1
}

* Export results
global ress "bb cc"
foreach j of global ress {
    esttab `j'* , star("*" 0.1 "**" 0.05 "***" 0.01) b(%10.4f) t(%10.2f) ///
        scalars(N r2) sfmt(%10.3f) mtitles replace
}




/****************************************************************************************
  FIGURES 2-4
****************************************************************************************/

clear all
set more off

cd "$FOLDER"
use aggregate_day_all, clear

*---------------------------------------------------------------------------------------
* Panel time settings for L. and F. operators
*---------------------------------------------------------------------------------------
* Requires a panel id (call) and time variable (tradedate). Adjust if different.
xtset call tradedate, daily
egen dd = group(tradedate)
*---------------------------------------------------------------------------------------
* [-4, +4] window performance: generate PRu_t4_1..8 and PRw_t4_1..8
* Reference is t-4 (L4.*)
*---------------------------------------------------------------------------------------
cap drop PRu_t4_*
cap drop PRw_t4_*

local gg = 1
forvalues i = -3/0 {
    local j = -`i'
    quietly gen PRu_t4_`gg' = (log(L`j'.u_price) - log(L4.u_price))
    quietly gen PRw_t4_`gg' = (log(L`j'.w_price) - log(L4.w_price))
    local gg = `gg' + 1
}
forvalues i = 1/4 {
    quietly gen PRu_t4_`gg' = (log(F`i'.u_price) - log(L4.u_price))
    quietly gen PRw_t4_`gg' = (log(F`i'.w_price) - log(L4.w_price))
    local gg = `gg' + 1
}

*---------------------------------------------------------------------------------------
* [-4, +4] window for CONNECTIONS: level differences and log-differences vs t-4
* vars2 expands to names that will be appended to "conn" in the data: conn_ins_all, etc.
*---------------------------------------------------------------------------------------
global vars2 "_ins_all _ins_gemm A_ins_all A_ins_gemm P_ins_all P_ins_gemm"

foreach jj of global vars2  {
    local gg = 1
    forvalues i = -3/0 {
        local j = -`i'
        quietly gen D_`jj'_`gg'  = (L`j'.conn`jj' - L4.conn`jj')
        quietly gen DL_`jj'_`gg' = (log(L`j'.conn`jj') - log(L4.conn`jj'))
        local gg = `gg' + 1
    }
    forvalues i = 1/4 {
        quietly gen D_`jj'_`gg'  = (F`i'.conn`jj' - L4.conn`jj')
        quietly gen DL_`jj'_`gg' = (log(F`i'.conn`jj') - log(L4.conn`jj'))
        local gg = `gg' + 1
    }
}

*---------------------------------------------------------------------------------------
* Winsorise PRu/PRw 1–99% (uses _pctile for correct percentiles)
*---------------------------------------------------------------------------------------
global vars "PRu PRw"
foreach j of global vars {
    forvalues x = 1/8 {
        capture confirm variable `j'_t4_`x'
        if !_rc {
            quietly _pctile `j'_t4_`x', p(1 99)
            scalar p1  = r(r1)
            scalar p99 = r(r2)
            replace `j'_t4_`x' = p99 if `j'_t4_`x' > p99 & `j'_t4_`x' < .
            replace `j'_t4_`x' = p1  if `j'_t4_`x' < p1
        }
    }
}

*---------------------------------------------------------------------------------------
* Winsorise changes in connections (levels and logs) at 1–99%
*---------------------------------------------------------------------------------------
global vars7 "D__ins_all D__ins_gemm D_A_ins_all D_A_ins_gemm D_P_ins_all D_P_ins_gemm DL__ins_all DL__ins_gemm DL_A_ins_all DL_A_ins_gemm DL_P_ins_all DL_P_ins_gemm"

foreach j of global vars7 {
    forvalues x = 1/8 {
        capture confirm variable `j'_`x'
        if !_rc {
            quietly _pctile `j'_`x', p(1 99)
            scalar p1  = r(r1)
            scalar p99 = r(r2)
            replace `j'_`x' = p99 if `j'_`x' > p99 & `j'_`x' < .
            replace `j'_`x' = p1  if `j'_`x' < p1
        }
    }
}

*---------------------------------------------------------------------------------------
* Define rating change flags
*---------------------------------------------------------------------------------------
cap drop flag_ret_ch
gen flag_ret_ch = 0
replace flag_ret_ch = 1 if rating_change_consens != 0

* Across issuer (broader definition)
bys issuer tradedate: egen ISS_ret_ch = max(flag_ret_ch)
bys issuer tradedate: egen ISS_down_aux = sum(downgrade_consens)
bys issuer tradedate: egen ISS_up_aux = sum(upgrade_consens)

	gen iss_down=0
	replace iss_down=1 if ISS_down_aux>0 
	
	gen iss_up=0
	replace iss_up=1 if ISS_up_aux>0 

* Monthly group (if needed later)
capture egen mm = group(year month)

* Flag the days that coincided with rating changes (any obs in date)
bys tradedate: egen flag_days = max(flag_ret_ch)

****************************************************************************************
** Figure - Step 8-day windows (Baseline → price effect)
****************************************************************************************
cap drop h bC* bT* up90b* lo90b*
gen h = _n   /* h is the horizon index (1..8 will be used) */
quietly gen bTRAN     = 0
quietly gen bCENT     = 0
quietly gen up90bCENT = 0
quietly gen lo90bCENT = 0
quietly gen up90bTRAN = 0
quietly gen lo90bTRAN = 0

forvalues i = 1/8 {
    di `i'
    quietly {
        cap drop aux* yy*
        gen yy1 = abs(100 * PRw_t4_`i')   /* NEW BASELINE */

        * Shock: rating change (issuer-day level)
        gen auxxx = ISS_ret_ch
        local shock auxxx

        * NOTE: absorb() includes instrumentid#year and dd if present.
        capture confirm variable dd
        if !_rc {
            reghdfe yy1 `shock' if flag_days == 1, absorb(instrumentid#year dd) vce(cluster instrumentid)
        }
        else {
            reghdfe yy1 `shock' if flag_days == 1, absorb(instrumentid#year) vce(cluster instrumentid)
        }

        gen aux1 = _b[`shock']
        gen aux2 = _se[`shock']

        ***** 90% confidence bands *****
        scalar sig1 = 0.10
        quietly replace bCENT       = aux1 if h == `i' + 1
        quietly replace up90bCENT   = aux1 + invnormal(1 - sig1/2) * aux2 if h == `i' + 1
        quietly replace lo90bCENT   = aux1 - invnormal(1 - sig1/2) * aux2 if h == `i' + 1
    }
}

* 0-line and centered horizon
cap drop bzero
gen bzero = 0

cap drop h2
gen h2 = h - 5

tw (scatter up90bCENT h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter lo90bCENT h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter bCENT     h2, xscale(range(-4 4)) xlabel(-4(1)4) c(l) msize(1.8) mcolor(black) lcolor(black) lwidth(medthick)) ///
   (lfit bzero h2, xline(0, lcolor(blue)) lcolor(red)) if h2 <= 4, ///
   graphregion(color(white)) legend(off) xtitle("TRADING DAYS", size(medium)) ///
   name("basee2", replace)

****************************************************************************************
** Figure 3 - up vs downgrades (kept baseline form; shock redefined explicitly)
****************************************************************************************

cap drop h bC* bT* up90b* lo90b*
gen h = _n
quietly gen bTRAN     = 0
quietly gen bCENT     = 0
quietly gen up90bCENT = 0
quietly gen lo90bCENT = 0
quietly gen up90bTRAN = 0
quietly gen lo90bTRAN = 0

forvalues i = 1/8 {
    di `i'
    quietly {
        cap drop aux* yy*
        gen yy1 = abs(100 * PRw_t4_`i')   /* NEW BASELINE */

        * Re-affirm shock to avoid ambiguity
        gen auxxx = iss_up
        local shock auxxx


            reghdfe yy1 `shock' if flag_days == 1, absorb(instrumentid#year dd) vce(cluster instrumentid)


        gen aux1 = _b[`shock']
        gen aux2 = _se[`shock']

        scalar sig1 = 0.10
        quietly replace bCENT       = aux1 if h == `i' + 1
        quietly replace up90bCENT   = aux1 + invnormal(1 - sig1/2) * aux2 if h == `i' + 1
        quietly replace lo90bCENT   = aux1 - invnormal(1 - sig1/2) * aux2 if h == `i' + 1
    }
}

cap drop bzero
gen bzero = 0

cap drop h2
gen h2 = h - 5

tw (scatter up90bCENT h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter lo90bCENT h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter bCENT     h2, xscale(range(-4 4)) xlabel(-4(1)4) c(l) msize(1.8) mcolor(black) lcolor(black) lwidth(medthick)) ///
   (lfit bzero h2, xline(0, lcolor(blue)) lcolor(red)) if h2 <= 4, ///
          title("Upgrades", size(large)) graphregion(color(white)) legend(off) ///
   graphregion(color(white)) legend(off) xtitle("TRADING DAYS", size(medium)) ///
   name("basee4", replace)

cap drop h bC* bT* up90b* lo90b*
gen h = _n
quietly gen bTRAN     = 0
quietly gen bCENT     = 0
quietly gen up90bCENT = 0
quietly gen lo90bCENT = 0
quietly gen up90bTRAN = 0
quietly gen lo90bTRAN = 0

forvalues i = 1/8 {
    di `i'
    quietly {
        cap drop aux* yy*
        gen yy1 = abs(100 * PRw_t4_`i')   /* NEW BASELINE */

        * Re-affirm shock again for clarity
        gen auxxx = iss_down
        local shock auxxx

            reghdfe yy1 `shock' if flag_days == 1, absorb(instrumentid#year dd) vce(cluster instrumentid)

        gen aux1 = _b[`shock']
        gen aux2 = _se[`shock']

        scalar sig1 = 0.10
        quietly replace bCENT       = aux1 if h == `i' + 1
        quietly replace up90bCENT   = aux1 + invnormal(1 - sig1/2) * aux2 if h == `i' + 1
        quietly replace lo90bCENT   = aux1 - invnormal(1 - sig1/2) * aux2 if h == `i' + 1
    }
}

cap drop bzero
gen bzero = 0

cap drop h2
gen h2 = h - 5

tw (scatter up90bCENT h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter lo90bCENT h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter bCENT     h2, xscale(range(-4 4)) xlabel(-4(1)4) c(l) msize(1.8) mcolor(black) lcolor(black) lwidth(medthick)) ///
   (lfit bzero h2, xline(0, lcolor(blue)) lcolor(red)) if h2 <= 4, ///
          title("Downgrades", size(large)) graphregion(color(white)) legend(off) ///
   graphregion(color(white)) legend(off) xtitle("TRADING DAYS", size(medium)) ///
   name("basee3", replace)

graph combine basee4 basee3, ycommon graphregion(color(white)) name("up_down", replace)


****************************************************************************************
** Figure 4 - sophisticated vs unsophisticated investors
****************************************************************************************

global vars7 "ins_gemm"

foreach j of global vars7 {
    cap drop h bC* bT* up90b* lo90b*
    gen h = _n
    quietly gen bTRAN     = 0
    quietly gen bCENT     = 0
    quietly gen up90bCENT = 0
    quietly gen lo90bCENT = 0
    quietly gen up90bTRAN = 0
    quietly gen lo90bTRAN = 0

    forvalues i = 1/8 {
        di `i'
        quietly {
            cap drop aux* yy*
            gen yy1 = D_A_`j'_`i'
            gen yy2 = D_P_`j'_`i'

            * Shock: rating change (issuer-day level)
            gen auxxx = ISS_ret_ch
            local shock auxxx

            capture confirm variable dd
            if !_rc {
                reghdfe yy1 `shock' if flag_days == 1, absorb(instrumentid#year dd) vce(cluster instrumentid)
            }
            else {
                reghdfe yy1 `shock' if flag_days == 1, absorb(instrumentid#year) vce(cluster instrumentid)
            }
            gen aux1 = _b[`shock']
            gen aux2 = _se[`shock']

            if !_rc {
                reghdfe yy2 `shock' if flag_days == 1, absorb(instrumentid#year dd) vce(cluster instrumentid)
            }
            else {
                reghdfe yy2 `shock' if flag_days == 1, absorb(instrumentid#year) vce(cluster instrumentid)
            }
            gen aux3 = _b[`shock']
            gen aux4 = _se[`shock']

            scalar sig1 = 0.10
            quietly replace bCENT       = aux1 if h == `i' + 1
            quietly replace up90bCENT   = aux1 + invnormal(1 - sig1/2) * aux2 if h == `i' + 1
            quietly replace lo90bCENT   = aux1 - invnormal(1 - sig1/2) * aux2 if h == `i' + 1

            quietly cap replace bTRAN       = aux3 if h == `i' + 1
            quietly cap replace up90bTRAN   = aux3 + invnormal(1 - sig1/2) * aux4 if h == `i' + 1
            quietly cap replace lo90bTRAN   = aux3 - invnormal(1 - sig1/2) * aux4 if h == `i' + 1
        }
    }

    cap drop bzero
    gen bzero = 0

    cap drop h2
    gen h2 = h - 5

    tw (scatter up90bCENT h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
       (scatter lo90bCENT h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
       (scatter bCENT     h2, xscale(range(-4 4)) xlabel(-4(1)4) c(l) msize(1.8) mcolor(black) lcolor(black) lwidth(medthick)) ///
       (lfit bzero h2, xline(0, lcolor(blue)) lcolor(red)) if h2 <= 4, ///
       title("Sophisticated Investors", size(large)) graphregion(color(white)) legend(off) ///
       xtitle("TRADING DAYS", size(medium)) name("fig1", replace)

    tw (scatter up90bTRAN h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
       (scatter lo90bTRAN h2, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
       (scatter bTRAN     h2, xscale(range(-4 4)) xlabel(-4(1)4) c(l) msize(1.8) mcolor(black) lcolor(black) lwidth(medthick)) ///
       (lfit bzero h2, xline(0, lcolor(blue)) lcolor(red)) if h2 <= 4, ///
       title("Unsophisticated Investors", size(large)) graphregion(color(white)) legend(off) ///
       xtitle("TRADING DAYS", size(medium)) name("fig2", replace)

    graph combine fig1 fig2, ycommon graphregion(color(white)) name("simp2_d`j'", replace)
}






****************
*** Table 5 ****
****************
clear all
set more off

cd "$FOLDER"

*-----------------------------
* Part 1: Aggregate connections
*-----------------------------
use Perf2020jan_COVID, clear

* Generate unique connection IDs: call × coun
egen cc = group(call coun)

* -- Day-level: all connections, all clients
bys tradedate: egen conn_agg_all = nvals(cc)
bys tradedate: egen call_agg_all = nvals(call)

* -- Day-level: against dealers only, all clients
cap drop aux*
bys tradedate: egen aux  = nvals(cc)   if counTy == 12
bys tradedate: egen auxb = nvals(call) if counTy == 12
bys tradedate: egen conn_agg_gemm = min(aux)
bys tradedate: egen call_agg_gemm = min(auxb)

* -- Day-level: all connections, active only
bys tradedate: egen aux2  = nvals(cc)   if active == 1
bys tradedate: egen aux2b = nvals(call) if active == 1
bys tradedate: egen connA_agg_all = min(aux2)
bys tradedate: egen callA_agg_all = min(aux2b)

* -- Day-level: dealers only, active only
bys tradedate: egen aux3  = nvals(cc)   if counTy == 12 & active == 1
bys tradedate: egen aux3b = nvals(call) if counTy == 12 & active == 1
bys tradedate: egen connA_agg_gemm = min(aux3)
bys tradedate: egen callA_agg_gemm = min(aux3b)

* -- Day-level: all connections, passive only
bys tradedate: egen aux4  = nvals(cc)   if passive == 1
bys tradedate: egen aux4b = nvals(call) if passive == 1
bys tradedate: egen connP_agg_all = min(aux4)
bys tradedate: egen callP_agg_all = min(aux4b)

* -- Day-level: dealers only, passive only
bys tradedate: egen aux5  = nvals(cc)   if counTy == 12 & passive == 1
bys tradedate: egen aux5b = nvals(call) if counTy == 12 & passive == 1
bys tradedate: egen connP_agg_gemm = min(aux5)
bys tradedate: egen callP_agg_gemm = min(aux5b)

*-----------------------------
* Day-level size variables
*-----------------------------
cap drop aux*
bys tradedate: egen DailyVol   = total(quantity)
bys tradedate: egen aux1       = total(quantity) if counTy == 12
bys tradedate: egen aux2       = total(quantity) if active == 1             
bys tradedate: egen aux3       = total(quantity) if counTy == 12 & active == 1
bys tradedate: egen aux4       = total(quantity) if passive == 1
bys tradedate: egen aux5       = total(quantity) if counTy == 12 & passive == 1

bys tradedate: egen DailyVol_g  = min(aux1)
bys tradedate: egen DailyVol_A  = min(aux2)
bys tradedate: egen DailyVol_Ag = min(aux3)
bys tradedate: egen DailyVol_P  = min(aux4)
bys tradedate: egen DailyVol_Pg = min(aux5)

* One row per day
duplicates drop tradedate, force
sort tradedate
format tradedate %td
save CB_spread_daily, replace


*---------------------------------------------
* Part 2: Import Corporate Bond spreads (daily)
*---------------------------------------------
import excel "cb_spreads.xlsx", sheet("Data") cellrange(B31:I6198) clear
keep B F I
rename B tradedate
rename F spread_IG
rename I spread_HY

* Try to ensure tradedate is daily date
capture confirm numeric variable tradedate
if _rc {
    gen double tradedate_num = daily(tradedate, "YMD")
    replace tradedate_num = daily(tradedate, "DMY") if missing(tradedate_num)
    drop tradedate
    rename tradedate_num tradedate
}
format tradedate %td
sort tradedate
save spreads_2020dec, replace


*---------------------------------------------------------
* Part 3: Merge trade-aggregated connections with spreads
*---------------------------------------------------------
use CB_spread_daily, clear
merge 1:1 tradedate using spreads_2020dec, keep(3) nogen

* Logs of daily volumes (prefix L*)
global vars3 "DailyVol DailyVol_g DailyVol_A DailyVol_Ag DailyVol_P DailyVol_Pg"
cap drop LDailyVol*
foreach j of global vars3 {
    gen L`j' = log(`j')
}

rename LDailyVol     L_agg_all
rename LDailyVol_g   L_agg_gemm
rename LDailyVol_A   LA_agg_all
rename LDailyVol_Ag  LA_agg_gemm
rename LDailyVol_P   LP_agg_all
rename LDailyVol_Pg  LP_agg_gemm

* Time-series settings
sort tradedate
format tradedate %td
tsset tradedate, daily

* First differences and one-step leads of differences
gen Dspread_IG  = D.spread_IG
gen Dspread_HY  = D.spread_HY
gen FDspread_IG = F.Dspread_IG
gen FDspread_HY = F.Dspread_HY

* Crisis flag: Feb–Apr 2020
capture confirm variable year
if _rc gen year  = year(tradedate)
capture confirm variable month
if _rc gen month = month(tradedate)

cap drop crisis
gen byte crisis = 0
replace crisis = 1 if year == 2020 & inlist(month, 2, 3, 4)

*---------------------------------
* Table: spreads on connections
*---------------------------------
* Target suffixes for variables: use consistent suffixes that match conn_*, call_*, L* created above
global varsC "_agg_all _agg_gemm"
global vars2 "FDspread_IG FDspread_HY"

foreach i of global varsC {
    foreach j of global vars2 {
        di "`j'_`i'"

        quietly {
            cap estimates drop aa*

            cap drop yy xx xxVol xxCli xx_crisis
            gen yy    = `j'
            gen xx    = conn`i'     // connections
            gen xxVol = L`i'        // log daily volume (matching suffix)
            gen xxCli = call`i'     // number of clients/calls

            gen xx_crisis = xx * crisis

            * Spec 1: baseline + crisis interaction
            reg yy xx xx_crisis, vce(robust)
            estimates store aa1

            * Spec 2: + volume
            reg yy xx xx_crisis xxVol, vce(robust)
            estimates store aa2

            * Spec 3: + client count
            reg yy xx xx_crisis xxVol xxCli, vce(robust)
            estimates store aa3
        }

        esttab aa* using spread_conn_`i'`j'.tex, ///
            replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
            b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f)
    }
}


************************************************************
* Table 6
************************************************************

cd "$FOLDER"
use aggregate_INS_all_COVID, clear   /* 3-D level: Performance computed against all counterparties */

*-----------------------------------------------------------
* Rename to shorten variable names
*-----------------------------------------------------------
forvalues i = 0/30 {
    capture rename dimTS`i'ClientUnw      dim`i'Unw
    capture rename dimTS`i'ClientWeighted dim`i'W
}

*-----------------------------------------------------------
* If unweighted is missing, set weighted to missing too
*-----------------------------------------------------------
forvalues i = 0/30 {
    di `i'
    capture confirm variable dim`i'Unw
    if !_rc {
        replace dim`i'W = . if dim`i'Unw == .
    }
}

*-----------------------------------------------------------
* Winsorise (Weighted series)
*-----------------------------------------------------------
global winlist "W"
foreach x of global winlist {
    forvalues i = 0/30 {
        capture confirm variable dim`i'`x'
        if !_rc {
            quietly _pctile dim`i'`x', p(1 99)
            scalar p1  = r(r1)
            scalar p99 = r(r2)
            replace dim`i'`x' = p99 if dim`i'`x' > p99 & dim`i'`x' < .
            replace dim`i'`x' = p1  if dim`i'`x' < p1
        }
    }
}

*-----------------------------------------------------------
* Define the 2 controls (safe logs)
*-----------------------------------------------------------
gen size    = log(clientQuantityDaily) if clientQuantityDaily > 0
gen logTRAN = log(transactionDaily)    if transactionDaily > 0

* Winsorize selected covariates at 1–99%
global winlist "day_OR1_bip day_OR1_ful day_INS_ful day_INS_bip logTRAN size"
foreach x of global winlist {
    capture confirm variable `x'
    if !_rc {
        quietly _pctile `x', p(1 99)
        scalar p1  = r(r1)
        scalar p99 = r(r2)
        replace `x' = p99 if `x' > p99 & `x' < .
        replace `x' = p1  if `x' < p1
    }
}

* Time index used in FE interactions
capture drop mm
gen mm = tradedate


**********************
* Regression analysis *
**********************
egen call2 = group(call)

********* TABLE 1 **********************
global vars "1 5 10 15 25"

cap estimates drop aa*
cap estimates drop bb*
cap estimates drop cc*
cap estimates drop dd*
cap estimates drop ee*
cap estimates drop ff*
cap estimates drop gg*
cap estimates drop hh*

*** GOLDSTEIN windows
capture drop crisis
gen byte crisis = 0
replace crisis = 1 if year == 2020 & month == 2

capture drop crisis2
gen byte crisis2 = 0
replace crisis2 = 1 if year == 2020 & month == 3 & day < 14

capture drop crisis3
gen byte crisis3 = 0
replace crisis3 = 1 if year == 2020 & (month == 3 & day > 13)
replace crisis3 = 1 if year == 2020 & month == 4

local gg = 1
foreach j of global vars {
    di `gg'

    cap drop yy* zz*
    gen yy = 100 * dim`j'W   

    cap drop R_*
    gen R_cent_ful = day_INS_ful
    gen R_cent_bip = day_INS_bip
    gen R_size     = size
    gen R_tran     = logTRAN

    gen R_cent_ful_crisis  = day_INS_ful * crisis
    gen R_cent_ful_crisis2 = day_INS_ful * crisis2
    gen R_cent_ful_crisis3 = day_INS_ful * crisis3

    **** First table: baseline (Weighted)
    reghdfe yy R_cent_ful R_cent_ful_crisis R_cent_ful_crisis2 R_cent_ful_crisis3 R_size ///
        if active == 1 & transactionDaily > 0, ///
        absorb(mm#call2 instrumentid#year) vce(cluster call2 mm)
    estimates store aa`gg'

    local gg = `gg' + 1
}

* Export Panel A
global ress "aa"
foreach j of global ress {
    esttab `j'* using covid_table1.tex, ///
        replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
        b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f) ///
        keep(R_*)
}

********* Panel B **********************
global vars "1 5 10 15 25"

cap estimates drop aa*
cap estimates drop bb*
cap estimates drop cc*
cap estimates drop dd*
cap estimates drop ee*
cap estimates drop ff*
cap estimates drop gg*
cap estimates drop hh*

capture drop crisis0
gen byte crisis0 = 0 // pre UK news
replace crisis0 = 1 if year == 2020 & month == 3 & day > 13 & day < 19

capture drop crisis
gen byte crisis = 0 // [post-UK] pre US news
replace crisis = 1 if year == 2020 & month == 3 & day > 18 & day < 24

capture drop crisis2
gen byte crisis2 = 0 // post announcements
replace crisis2 = 1 if year == 2020 & month == 3 & day > 23
replace crisis2 = 1 if year == 2020 & month == 4

local gg = 1
foreach j of global vars {
    di `gg'

    cap drop yy* zz*
    gen yy = 100 * dim`j'W
    gen zz = 100 * dim`j'Unw

    cap drop R_*
    gen R_cent_ful = day_INS_ful
    gen R_cent_bip = day_INS_bip
    gen R_size     = size
    gen R_tran     = logTRAN

    gen R_cent_ful_crisis0 = day_INS_ful * crisis0
    gen R_cent_ful_crisis  = day_INS_ful * crisis
    gen R_cent_ful_crisis2 = day_INS_ful * crisis2

    **** First table: baseline (Weighted)
    reghdfe yy R_cent_ful R_cent_ful_crisis0 R_cent_ful_crisis R_cent_ful_crisis2 R_size ///
        if active == 1 & transactionDaily > 0, ///
        absorb(mm#call2 instrumentid#year) vce(cluster call2 mm)
    estimates store aa`gg'

    local gg = `gg' + 1
}

* Export Panel B
global ress "aa"
foreach j of global ress {
    esttab `j'* using covid_table2.tex, ///
        replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
        b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f) ///
        keep(R_*)
}




************************************************************
* Table 7: IV Regressions 
************************************************************

cd "$FOLDER"
use aggregate_INS_all, clear   /* 3-D level : Performance computed against all counterparties */

*-----------------------------------------------------------
* Rename to shorten variable names
*-----------------------------------------------------------
forvalues i = 0/30 {
    capture rename dimTS`i'ClientUnw      dim`i'Unw
    capture rename dimTS`i'ClientWeighted dim`i'W
}

*-----------------------------------------------------------
* If unweighted is missing, set weighted to missing too
*-----------------------------------------------------------
forvalues i = 0/30 {
    di `i'
    capture confirm variable dim`i'Unw
    if !_rc {
        replace dim`i'W = . if dim`i'Unw == .
    }
}

*-----------------------------------------------------------
* Winsorise weighted performance series at 1–99%
*-----------------------------------------------------------
forvalues i = 0/30 {
    capture confirm variable dim`i'W
    if !_rc {
        quietly _pctile dim`i'W, p(1 99)
        scalar p1  = r(r1)
        scalar p99 = r(r2)
        replace dim`i'W = p99 if dim`i'W > p99 & dim`i'W < .
        replace dim`i'W = p1  if dim`i'W < p1
    }
}

*-----------------------------------------------------------
* Winsorise day_INS_ful at 1–99%
*-----------------------------------------------------------
capture confirm variable day_INS_ful
if !_rc {
    quietly _pctile day_INS_ful, p(1 99)
    scalar p1  = r(r1)
    scalar p99 = r(r2)
    replace day_INS_ful = p99 if day_INS_ful > p99 & day_INS_ful < .
    replace day_INS_ful = p1  if day_INS_ful < p1
}

* Time index used in FE interactions
capture drop mm
gen mm = tradedate

*-----------------------------------------------------------
* Leave-one-out (issuer × day) instrument:
* avg_day_INS_ful_excl_i = mean of day_INS_ful among other bonds
*-----------------------------------------------------------
bysort issuer tradedate: egen total_day_INS_ful = total(day_INS_ful)
bysort issuer tradedate: egen count_day_INS_ful = count(day_INS_ful)

gen total_day_INS_ful_excl_i = total_day_INS_ful - day_INS_ful
gen count_day_INS_ful_excl_i = count_day_INS_ful - 1
gen avg_day_INS_ful_excl_i   = total_day_INS_ful_excl_i / count_day_INS_ful_excl_i

* winsorize instrument at 1–99%
cap which winsor2
if _rc {
    quietly _pctile avg_day_INS_ful_excl_i, p(1 99)
    scalar p1i  = r(r1)
    scalar p99i = r(r2)
    replace avg_day_INS_ful_excl_i = p99i if avg_day_INS_ful_excl_i > p99i & avg_day_INS_ful_excl_i < .
    replace avg_day_INS_ful_excl_i = p1i  if avg_day_INS_ful_excl_i < p1i
}
else {
    winsor2 avg_day_INS_ful_excl_i, replace cuts(1 99)
}

*-----------------------------------------------------------
* Scale dependent variables to percentage points
*-----------------------------------------------------------
capture confirm variable dim5W
if !_rc replace dim5W  = dim5W  * 100
capture confirm variable dim10W
if !_rc replace dim10W = dim10W * 100
capture confirm variable dim15W
if !_rc replace dim15W = dim15W * 100

*-----------------------------------------------------------
* IV regressions with high-dimensional FE
*-----------------------------------------------------------

reghdfe dim5W size (day_INS_ful =avg_day_INS_ful_excl_i) if active == 1 & transactionDaily>0, vce(robust) absorb(mm#call) stage(first)
estimates store aa

reghdfe dim10W size (day_INS_ful =avg_day_INS_ful_excl_i) if active == 1 & transactionDaily>0, vce(robust) absorb(mm#call) stage(first)
estimates store bb

reghdfe dim15W size (day_INS_ful =avg_day_INS_ful_excl_i) if active == 1 & transactionDaily>0, vce(robust) absorb(mm#call) stage(first)
estimates store cc

*-----------------------------------------------------------
* Export results
*-----------------------------------------------------------
esttab aa bb cc using rr_iv.tex, ///
    replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
    b(%10.4f) t(%10.2f) scalars(N) sfmt(%10.3f) 




************************************************************
* Table 8: 2D regressions 
************************************************************

cd "$FOLDER"

use aggregate_day_all, clear   /* BASELINE */

*-----------------------------------------------------------
* Rename to shorten variable names + align weighted/unweighted
*-----------------------------------------------------------
forvalues i = 0/30 {
    capture rename dimTS`i'ClientUnw      dim`i'Unw
    capture rename dimTS`i'ClientWeighted dim`i'W
    capture confirm variable dim`i'Unw
    if !_rc {
        replace dim`i'W = . if dim`i'Unw == .
    }
}

* (kept from original; redundant but harmless)
forvalues i = 0/20 {
    capture confirm variable dim`i'Unw
    if !_rc {
        replace dim`i'W = . if dim`i'Unw == .
    }
}

*-----------------------------------------------------------
* Winsorise (1–99%) for W and Unw
*-----------------------------------------------------------
global winlist "W Unw"
foreach x of global winlist {
    forvalues i = 0/30 {
        capture confirm variable dim`i'`x'
        if !_rc {
            quietly _pctile dim`i'`x', p(1 99)
            scalar p1  = r(r1)
            scalar p99 = r(r2)
            replace dim`i'`x' = p99 if dim`i'`x' > p99 & dim`i'`x' < .
            replace dim`i'`x' = p1  if dim`i'`x' < p1
        }
    }
}

*-----------------------------------------------------------
* Define the 2 controls (safe logs) and winsorize key covariates
*-----------------------------------------------------------
gen size    = log(clientQuantityDaily) if clientQuantityDaily > 0
gen logTRAN = log(transactionDaily)    if transactionDaily > 0

global winlist "day_OR1_bip day_OR1_ful day_INS_ful day_INS_bip logTRAN size"
foreach x of global winlist {
    capture confirm variable `x'
    if !_rc {
        quietly _pctile `x', p(1 99)
        scalar p1  = r(r1)
        scalar p99 = r(r2)
        replace `x' = p99 if `x' > p99 & `x' < .
        replace `x' = p1  if `x' < p1
    }
}

drop mm
gen mm = tradedate

xtset call mm

** BASELINE PERFORMANCE
global vars "5 10 15"

cap estimates drop aa*
cap estimates drop bb*
cap estimates drop cc*
cap estimates drop dd*

local gg = 1
foreach j of global vars {
    di `gg'
    quietly {
        cap drop yy* zz*
        gen yy = 100 * dim`j'W
        gen zz = 100 * dim`j'Unw

        cap drop R_*
        gen R_cent_ful = day_OR1_ful
        gen R_cent_bip = day_OR1_bip
        gen R_size     = size
        gen R_tran     = logTRAN

        * With controls (size):
        reghdfe yy R_cent_ful R_size if active == 1 & transactionDaily > 0, ///
            absorb(mm call) vce(cluster call mm)
        estimates store aa`gg'

        reghdfe yy R_cent_bip R_size if active == 1 & transactionDaily > 0, ///
            absorb(mm call) vce(cluster call mm)
        estimates store bb`gg'

        reghdfe yy R_cent_ful R_size if active == 0 & transactionDaily > 0, ///
            absorb(mm call) vce(cluster call mm)
        estimates store cc`gg'

        reghdfe yy R_cent_bip R_size if active == 0 & transactionDaily > 0, ///
            absorb(mm call) vce(cluster call mm)
        estimates store dd`gg'
    }
    local gg = `gg' + 1
}

* Export results
global ress "aa bb cc dd"
foreach j of global ress {
    esttab `j'*, ///
        star("*" 0.1 "**" 0.05 "***" 0.01) ///
        b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f) ///
        keep(R_*) mtitles replace
}




************************************************************
* Table 9: Horizons
************************************************************


cd "$FOLDER"

use aggregate_INS_all_horizons, clear   

*-----------------------------------------------------------
* Rename to shorten variable names
*-----------------------------------------------------------
forvalues i = 0/40 {
    capture rename dimTS`i'ClientUnw      dim`i'Unw
    capture rename dimTS`i'ClientWeighted dim`i'W
}

*-----------------------------------------------------------
* If unweighted is missing, set weighted to missing as well
* (original comment said "zero", code actually used missing)
*-----------------------------------------------------------
forvalues i = 0/40 {
    di `i'
    capture confirm variable dim`i'Unw
    if !_rc {
        replace dim`i'W = . if dim`i'Unw == .
    }
}

*-----------------------------------------------------------
* Winsorise (Weighted series, 1–99%)
*-----------------------------------------------------------
forvalues i = 0/40 {
    capture confirm variable dim`i'W
    if !_rc {
        quietly _pctile dim`i'W, p(1 99)
        scalar p1  = r(r1)
        scalar p99 = r(r2)
        replace dim`i'W = p99 if dim`i'W > p99 & dim`i'W < .
        replace dim`i'W = p1  if dim`i'W < p1
    }
}

*-----------------------------------------------------------
* Define controls (safe logs)
*-----------------------------------------------------------
gen size    = log(clientQuantityDaily) if clientQuantityDaily > 0
gen logTRAN = log(transactionDaily)    if transactionDaily > 0

* Winsorize weekly/monthly intensity proxies + controls (1–99%)
cap which winsor2
if _rc {
    foreach v in week_INS_ful week_INS_bip month_INS_ful month_INS_bip logTRAN size {
        capture confirm variable `v'
        if !_rc {
            quietly _pctile `v', p(1 99)
            scalar p1  = r(r1)
            scalar p99 = r(r2)
            replace `v' = p99 if `v' > p99 & `v' < .
            replace `v' = p1  if `v' < p1
        }
    }
}
else {
    winsor2 week_INS_ful week_INS_bip month_INS_ful month_INS_bip logTRAN size, replace cuts(1 99)
}

* Time index for FE interactions
capture drop mm
gen mm = tradedate

**********************
* Regression analysis (Weekly windows)
**********************
global vars "5 15 25"

cap estimates drop aa*
cap estimates drop bb*
cap estimates drop cc*
cap estimates drop dd*
cap estimates drop ee*
cap estimates drop ff*
cap estimates drop gg*
cap estimates drop hh*

local gg = 1
foreach j of global vars {
    di `gg'

    cap drop yy*
    gen yy = 100 * dim`j'W

    cap drop R_*
    gen R_cent_ful = week_INS_ful
    gen R_cent_bip = week_INS_bip
    gen R_size     = size
    gen R_tran     = logTRAN

    **** First table: baseline (Weighted)
    reghdfe yy R_cent_ful R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    estimates store aa`gg'

    reghdfe yy R_cent_bip R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    estimates store bb`gg'

    local gg = `gg' + 1
}

* Export weekly results
global ress "aa bb"
foreach j of global ress {
    esttab `j'* using rr_`j'.tex, ///
        replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
        b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f) mtitles
}

**********************
* Regression analysis (Monthly windows)
**********************
global vars "5 15 25"

cap estimates drop aa*
cap estimates drop bb*
cap estimates drop cc*
cap estimates drop dd*
cap estimates drop ee*
cap estimates drop ff*
cap estimates drop gg*
cap estimates drop hh*

local gg = 1
foreach j of global vars {
    di `gg'

    cap drop yy*
    gen yy = 100 * dim`j'W

    cap drop R_*
    gen R_cent_ful = month_INS_ful
    gen R_cent_bip = month_INS_bip
    gen R_size     = size
    gen R_tran     = logTRAN

    **** First table: baseline (Weighted)
    reghdfe yy R_cent_ful R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    estimates store cc`gg'

    reghdfe yy R_cent_bip R_size if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    estimates store dd`gg'

    local gg = `gg' + 1
}

* Export monthly results
global ress "cc dd"
foreach j of global ress {
    esttab `j'* using rr_`j'.tex, ///
        replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
        b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f) mtitles
}




************************************************************
* TABLE 10: Informed Dealer Test
************************************************************
cd "$FOLDER"

use Perf2020jan, clear

* Drop trades where the client trades with itself
drop if call == coun

*-----------------------------------------------------------
* Compute %-return on each transaction (signed by bs_clients)
* for horizons up to 30 days
*-----------------------------------------------------------
cap drop dim*
forvalues i = 1/30 {
    di `i'
    qui gen dimProfitUnw_`i' = (log(priceU_d`i') - log(price)) * bs_clients
    qui winsor2 dimProfitUnw_`i', replace cuts(1 99)

    * Weighted by consideration and quantity
    qui bys call tradedate: egen dimW_`i'  = wtmean(dimProfitUnw_`i'), weight(correctedconsideration)
    qui bys call tradedate: egen dimWq_`i' = wtmean(dimProfitUnw_`i'), weight(quantity)

    * Performance against dealers only (counTy_modal == 12)
    cap drop aux
    qui bys call tradedate: egen aux = wtmean(dimProfitUnw_`i'), weight(quantity) if counTy_modal == 12
    qui bys call tradedate: egen dimWqG_`i' = min(aux)
}

*-----------------------------------------------------------
* Date components and monthly group
*-----------------------------------------------------------
gen dyear  = year(tradedate)
gen dmonth = month(tradedate)
egen mm    = group(dyear dmonth)

*-----------------------------------------------------------
* Aggregate daily stats
*-----------------------------------------------------------
bys call tradedate: egen clientQuantityDaily = total(quantity)
bys call tradedate instrumentid: egen INSQuantityDaily = total(quantity)

cap drop transactionDaily* aux*
gen auxn = _n
bys call tradedate: egen transactionDaily = nvals(auxn)

* Dealer-level aggregates
bys coun tradedate: egen DealerQuantityDaily = total(quantity)
bys coun tradedate: egen DealerConnect       = nvals(call)

*-----------------------------------------------------------
* Dealer buckets (3 tertiles by client volume per dealer-month)
*-----------------------------------------------------------
cap drop aux*
bys call mm coun: egen dealer_client_vol = total(quantity) if counTy == 12
bys call mm coun: gen aux = _n if counTy == 12
bys mm coun: egen aux_3 = xtile(dealer_client_vol), nq(3) if aux == 1
bys call mm coun: egen dealer_client_3 = min(aux_3)

*-----------------------------------------------------------
* Size variables and winsorisation
*-----------------------------------------------------------
gen sizeINS  = log(INSQuantityDaily)
gen size     = log(clientQuantityDaily)
gen sizeDeal = log(DealerQuantityDaily)

winsor2 sizeINS size sizeDeal day_OR1_ful DealerConnect, replace cuts(1 99)

*-----------------------------------------------------------
* Generate day-client and day-client-dealer flags
*-----------------------------------------------------------
bys call tradedate: gen Fauxn = _n
bys call coun tradedate: gen FauxD = _n

*-----------------------------------------------------------
* Regression analysis
*-----------------------------------------------------------
global vars "5 10 15"

cap estimates drop aa* bb* cc* dd*

local gg = 1
foreach j of global vars {
    di `gg'
    qui {
        cap drop yy*
        gen yy = 100 * dimWq_`j' if FauxD == 1 & counTy == 12
        winsor2 yy, replace cuts(1 99)

        cap drop R_*
        gen R_cent_ful      = day_OR1_ful if FauxD == 1 & counTy == 12
        gen R_size          = size        if FauxD == 1 & counTy == 12
        gen R_sizeDeal      = sizeDeal    if FauxD == 1 & counTy == 12
        gen R_DealerConnect = DealerConnect if FauxD == 1 & counTy == 12

        * Baseline: FE on tradedate, call, coun
        reghdfe yy R_cent_ful R_size if active == 1 & transactionDaily > 0, ///
            absorb(tradedate call coun) vce(cluster call tradedate)
        estimates store aa`gg'

        * Add dealer controls
        reghdfe yy R_cent_ful R_size R_sizeDeal R_DealerConnect if active == 1 & transactionDaily > 0, ///
            absorb(tradedate call coun) vce(cluster call tradedate)
        estimates store bb`gg'

        * FE with tradedate#coun
        reghdfe yy R_cent_ful R_size if active == 1 & transactionDaily > 0, ///
            absorb(tradedate#coun call) vce(cluster call tradedate)
        estimates store cc`gg'

        * FE with tradedate#coun#dealer_client_3
        reghdfe yy R_cent_ful R_size if active == 1 & transactionDaily > 0, ///
            absorb(tradedate#coun#dealer_client_3 call) vce(cluster call tradedate)
        estimates store dd`gg'
    }
    local gg = `gg' + 1
}

*-----------------------------------------------------------
* Export results
*-----------------------------------------------------------
global ress "aa bb cc dd"
foreach j of global ress {
    esttab `j'* using Dealer2_all_`j'.tex, ///
        replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
        b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f) ///
        keep(R_*) mtitles
}


************************************************************
* Table 11: decomposition 
************************************************************

cd "$FOLDER"

use aggregate_INS_all_adj, clear

*-----------------------------------------------------------
* Rename to shorten variable names
*-----------------------------------------------------------
forvalues i = 0/30 {
    capture rename dimTS`i'ClientUnw      dim`i'Unw
    capture rename dimTS`i'ClientWeighted dim`i'W
}

*-----------------------------------------------------------
* If unweighted is missing, set weighted to missing as well
*-----------------------------------------------------------
forvalues i = 0/30 {
    di `i'
    capture confirm variable dim`i'Unw
    if !_rc {
        replace dim`i'W = . if dim`i'Unw == .
    }
}

*-----------------------------------------------------------
* Winsorise series at 1–99%
*-----------------------------------------------------------
forvalues i = 0/30 {
    capture confirm variable dim`i'Unw
    if !_rc {
        quietly _pctile dim`i'Unw, p(1 99)
        scalar p1  = r(r1)
        scalar p99 = r(r2)
        replace dim`i'Unw = p99 if dim`i'Unw > p99 & dim`i'Unw < .
        replace dim`i'Unw = p1  if dim`i'Unw < p1
    }
}


forvalues i = 0/30 {
    capture confirm variable dim`i'W
    if !_rc {
        quietly _pctile dim`i'W, p(1 99)
        scalar p1  = r(r1)
        scalar p99 = r(r2)
        replace dim`i'W = p99 if dim`i'W > p99 & dim`i'W < .
        replace dim`i'W = p1  if dim`i'W < p1
    }
}

*-----------------------------------------------------------
* Define the 2 controls (safe logs), then winsorize covariates
*-----------------------------------------------------------
gen size    = log(clientQuantityDaily) if clientQuantityDaily > 0
gen logTRAN = log(transactionDaily)    if transactionDaily > 0

foreach x in day_OR1_bip day_OR1_ful day_INS_ful day_INS_bip logTRAN size {
    capture confirm variable `x'
    if !_rc {
        quietly _pctile `x', p(1 99)
        scalar p1  = r(r1)
        scalar p99 = r(r2)
        replace `x' = p99 if `x' > p99 & `x' < .
        replace `x' = p1  if `x' < p1
    }
}

* Time index for FE interactions
capture drop mm
gen mm = tradedate

**********************
* Regression analysis
**********************
global vars "5 10 15"

cap estimates drop aa*
cap estimates drop bb*
cap estimates drop cc*
cap estimates drop dd*
cap estimates drop ee*
cap estimates drop ff*
cap estimates drop gg*
cap estimates drop hh*

local gg = 1
foreach j of global vars {
    di `gg'

    cap drop yy* zz*
    gen yy = 100 * dim`j'W
    gen zz = 100 * dim`j'Unw

    cap drop R_*
    gen R_cent_ful = day_INS_ful
    gen R_cent_bip = day_INS_bip
    gen R_size     = size
    gen R_tran     = logTRAN

    * Weighted 
    reghdfe yy R_cent_bip R_size ///
        if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    estimates store bb`gg'

    * Unweighted 
    reghdfe zz R_cent_bip R_size ///
        if active == 1 & transactionDaily > 0, ///
        absorb(mm#call instrumentid#dyear) vce(cluster call mm)
    estimates store dd`gg'

    local gg = `gg' + 1
}

* Export results
global ress "bb dd"
foreach j of global ress {
    esttab `j'* , ///
        replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
        b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f) mtitles
}

*************
* PANEL B
*************

cd "$FOLDER"
use aggregate_INS_all, clear   /* 3-D level : Performance computed against all counterparties */


*-----------------------------------------------------------*
* Rename to shorten variable names
*-----------------------------------------------------------*
forvalues i = 0/30 {
    capture rename dimTS`i'ClientUnw      dim`i'Unw
    capture rename dimTS`i'ClientWeighted dim`i'W
}


*-----------------------------------------------------------*
* Winsorise the data 
*-----------------------------------------------------------*
global winlist "W Unw"
foreach x of global winlist {
    forvalues i = 0/30 {
        capture confirm variable dim`i'`x'
        if !_rc {
            quietly _pctile dim`i'`x', p(1 99)
            scalar p1 = r(r1)
            scalar p99 = r(r2)
            replace dim`i'`x' = p99 if dim`i'`x' > p99 & dim`i'`x' < .
            replace dim`i'`x' = p1  if dim`i'`x' < p1
        }
    }
}


*-----------------------------------------------------------*
* Define the 2 controls (safe logs)
*-----------------------------------------------------------*
gen size    = log(clientQuantityDaily) if clientQuantityDaily > 0
gen logTRAN = log(transactionDaily)    if transactionDaily > 0


* Winsorise selected covariates
global winlist "day_OR1_bip day_OR1_ful day_INS_ful day_INS_bip logTRAN size"
foreach x of global winlist {
    capture confirm variable `x'
    if !_rc {
        quietly _pctile `x', p(1 99)
        scalar p1 = r(r1)
        scalar p99 = r(r2)
        replace `x' = p99 if `x' > p99 & `x' < .
        replace `x' = p1  if `x' < p1
    }
}


drop mm
gen mm = tradedate

replace dim0W= dim0W*100
replace dim0Unw= dim0Unw*100

reghdfe dim0W day_INS_bip size if active == 1 & transactionDaily>0, absorb(mm#call instrumentid#dyear) cluster(call mm)
estimates store dd

reghdfe dim0Unw day_INS_bip size if active == 1 & transactionDaily>0, absorb(mm#call instrumentid#dyear) cluster(call mm)
estimates store ee

 esttab dd ee, ///
        replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
        b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f) ///
        mtitles

		

************************************************************
* Table 12: Cross-market analysis
************************************************************


use corp_gov, clear

* Horizons used in both the short regressions and long-horizon plots
global varLONG "5 10 15"

* Within (st0_date × call), count distinct typeG values; later filter to auxT==2
capture bys st0_date call: egen auxT = nvals(typeG)

* Drop any prior estimates
cap estimates drop *

************************************************************
* Short-horizon regressions (Table-style outputs)
************************************************************
local gg = 1
foreach j of global varLONG {
    di `gg'
    quietly {
        cap drop yy* zz*

        * Dependent variables (weighted/unweighted % points)
        gen yy = 100 * dimD_`j'W
        qui winsor2 yy, replace cuts(1 99)

        * Regressors and interactions
        cap drop R_*
        gen R_cent    = conn
        gen R_centD   = connD
        gen R_size    = size
        gen R_sizeD   = sizeD
        gen R_tran    = logTRAND
        gen R_inter   = R_cent  * (typeG - 1)
        gen R_interD  = R_centD * (typeG - 1)
        gen R_sizeinterD = R_sizeD * (typeG - 1)

        * Winsorize
        qui winsor2 R_size R_sizeD R_tran, replace cuts(1 99)

        * Perf. vs dealers; connections vs dealers; no Client×Market FE
        reghdfe yy R_interD R_centD R_size R_tran ///
            if auxT == 2 & activeB == 1, ///
            absorb(st0_date) vce(cluster call st0_date)
        estimates store aa`gg'

        * Perf. vs dealers; connections vs dealers; full FE (st0_date#call)
        reghdfe yy R_interD R_centD R_size R_tran ///
            if auxT == 2 & activeB == 1, ///
            absorb(st0_date#call) vce(cluster call st0_date)
        estimates store bb`gg'
    }
    local gg = `gg' + 1
}

* Export table
global ress "aa bb"
foreach j of global ress {
    esttab `j'* , ///
        replace star("*" 0.1 "**" 0.05 "***" 0.01) ///
        b(%10.4f) t(%10.2f) scalars(N r2) sfmt(%10.3f) mtitles
}

*******************
* Figure 5
*******************

* Preset variables to missing for later replace for IRFs
cap drop h bC* bT* up90b* lo90b*
gen h = _n - 1  /* h is the horizon for the IRFs */

quietly gen bTRAN       = .
quietly gen bTRAN2      = .
quietly gen bCENT       = .
quietly gen bCENT2      = .
quietly gen up90bCENT   = .
quietly gen lo90bCENT   = .
quietly gen up90bTRAN   = .
quietly gen lo90bTRAN   = .
quietly gen up90bCENT2  = .
quietly gen lo90bCENT2  = .
quietly gen up90bTRAN2  = .
quietly gen lo90bTRAN2  = .

forvalues i = 1/25 {
    di `i'
    quietly {
        cap drop aux*
		cap drop yy 
		cap drop Baux1
        gen yy = 100 * dimD_`i'W

        cap drop R_*
        gen R_cent  = connD
        gen R_size  = sizeD
        gen R_tran  = logTRAND
        gen R_inter = R_cent * (typeG - 1)

        qui winsor2 yy, replace cuts(1 99)
        qui winsor2 R_size, replace cuts(1 99)

        local shock R_inter

        * ActiveB == 1
        reghdfe yy `shock' R_cent R_size ///
            if transactionDaily > 0 & activeB == 1, ///
            absorb(st0_date#call typeG#st0_date typeG#call) vce(cluster call st0_date)
        gen aux1 = _b[`shock']
        gen aux2 = _se[`shock']

        ***** create confidence bands (90%) *****
        scalar sig1 = 0.10

        quietly replace bCENT       = aux1 if h == `i'
        quietly replace up90bCENT   = aux1 + invnormal(1 - sig1/2) * aux2 if h == `i'
        quietly replace lo90bCENT   = aux1 - invnormal(1 - sig1/2) * aux2 if h == `i'

    }
}

cap drop bzero
gen bzero = 0

*** FIGURES (black markers/lines; keep original titles)
tw (scatter up90bCENT  h, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter lo90bCENT  h, c(l) clp(dash) ms(i) mcolor(black) lcolor(black) lwidth(medthin)) ///
   (scatter bCENT      h, c(l) msize(1.3) mcolor(black) lcolor(black) lwidth(medthick)) ///
   (lfit bzero h, lcolor(red)) if h <= 25, ///
   graphregion(color(white)) legend(off) xtitle("TRADING DAYS") ///
   name("new_1b_call", replace)






